package code.excel.poi;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

/**
* <p></p>
*
* @version 1.0
* @author:huangwf
* @date:2017/8/21 13:57
* @history
*/

public class WriteToFile {

/**
* <p>数据写入Excel</p>
*
* @author:huangwf
* @date:2017/8/18 13:56
* @version 1.0
* @history
*/
public static void wirteToExcel(String filePathName, List<Map<String, String>> list, String sheetName) throws IOException, InvalidFormatException {
File file = new File(filePathName);
HSSFWorkbook workbook;
HSSFSheet sheet;
InputStream is = null;
if (!file.exists()) {
workbook = new HSSFWorkbook();
if (sheetName != null && "".equals(sheetName)) {
sheet = workbook.createSheet(sheetName);
} else {
sheet = workbook.createSheet("sheet1");
}
} else {
is = new FileInputStream(file);
workbook = (HSSFWorkbook) WorkbookFactory.create(is);
sheet = workbook.getSheetAt(0);
}
sheet.setColumnWidth(0, 25 * 256);
sheet.setColumnWidth(1, 25 * 256);

int lastRowNumber = sheet.getPhysicalNumberOfRows();
Row curRow = null;
for (Map<String, String> item : list) {
curRow = sheet.createRow(lastRowNumber);
curRow.createCell(0).setCellValue(item.get("jobName"));
curRow.createCell(1).setCellValue(item.get("jobId"));
++lastRowNumber;
}
OutputStream os = new FileOutputStream(file);
workbook.write(os);
os.close();
if (is != null) {
is.close();
}
}

/**
* <p>更新写入Txt文本</p>
*
* @author:huangwf
* @date:2017/8/21 14:05
* @version 1.0
* @history
*/
public static void witeToText(String str, String filePathName) {
try {
File file = new File(filePathName);
BufferedWriter output = new BufferedWriter(new FileWriter(file, true));
output.write(str);
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
